var express = require('express');
var router = express.Router();
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var fs = require('fs');
var config = require('../public/config');
var db = require('../public/javascripts/db');
var token = require('../public/javascripts/utils');
var async = require('async');
const imgPath = require('../public/config').imgPath;

function medicalRecord(num) {
    var length = String(num).length;
    var number;
    switch (length) {
        case 1:
            number = '000' + num;
            break;
        case 2:
            number = '00' + num;
            break;
        case 3:
            number = '0' + num;
            break;
        default:
            number = num;
    }
    return number;
}

function getMedicalNum(id, len) {
    var medicalNum = 'U' + medicalRecord(id) +
        token.getTime().split(' ')[0].split('-').join('') + medicalRecord(len);
    return medicalNum;
}

/* GET users listing. */
// router.post('/', function (req, res, next) {
router.post('/', multipartMiddleware, function (req, res, next) {
    //查看文件夹信息
    // var info = fs.statSync('/Users/michaelshan/Desktop/imageUpload');
    // console.log(info);

    // fs.readdir('/Users/michaelshan/Desktop/imageUpload', (err, files) => {
    //     if (err) {
    //         console.log(err);
    //         return;
    //     }
    //
    //     var count = files.length;
    //     console.log(count);
    // })

    console.log(req.files);
    var len = req.files.file.length;
    if (!len) {
        var name = new Date().getTime() + '.jpg';
        fs.rename(req.files.file.path, config.uploadImagePath + name, (err) => {
            if (err) {
                throw err;
            }
            var user = token.verifyToken(req.headers.token);
            var sql = 'SELECT * FROM user WHERE username = ?';

            db.query(sql, user, (err, result) => {
                if (err) {
                    throw err;
                    return;
                } else {
                    var sql2 = `SELECT * FROM images WHERE load_time between ${"'" + token.getTime().split(' ')[0] + ' 00:00:00' + "'"} and 
        ${"'" + token.getTime().split(' ')[0] + ' 23:59:59' + "'"}`;
                    db.query(sql2, (err2, result2) => {
                        if (err2) {
                            throw err2;
                            return;
                        } else {
                            var medicalNum = getMedicalNum(result[0].id, result2.length);
                            var imageSql = "INSERT INTO `images` (location,load_by,load_time,medical_num) VALUES (?,?,?,?)";
                            var imageParams = [imgPath + name, user, token.getTime(), medicalNum];
                            db.query(imageSql, imageParams, (err, result) => {
                                if (err) {
                                    throw err;
                                    return;
                                } else {
                                    console.log('image result', result)
                                    var data = {
                                        url: imgPath + name,
                                        medicalNum: medicalNum,
                                        id: result.insertId
                                    }
                                    res.send(data)
                                }
                            })
                        }
                    })
                    // console.log('result', String(result[0].id).length)


                }
            })
            // console.log('done!')
        })
    }
    else {
        var temp;
        var sql2 = `SELECT * FROM images WHERE load_time between ${"'" + token.getTime().split(' ')[0] + ' 00:00:00' + "'"} and 
                                    ${"'" + token.getTime().split(' ')[0] + ' 23:59:59' + "'"}`;
        db.query(sql2, (err2, result2) => {
            console.log('result2.length', result2.length)
            if (err2) {
                throw err2;
                return;
            } else {
                temp = result2.length;

                async.map(req.files.file, function (data1, callback1) {
                    var name = new Date().getTime() + Math.floor(Math.random() * 100) + '.jpg';
                    fs.rename(data1.path, config.uploadImagePath + name, (err) => {
                        if (err) {
                            throw err;
                        }
                        var user = token.verifyToken(req.headers.token);
                        var sql = 'SELECT * FROM user WHERE username = ?';
                        db.query(sql, user, (err, result) => {
                            if (err) {
                                throw err;
                                return;
                            } else {
                                var medicalNum = getMedicalNum(result[0].id, ++temp);
                                var imageSql = "INSERT INTO `images` (location,load_by,load_time,medical_num) VALUES (?,?,?,?)";
                                var imageParams = [imgPath + name, user, token.getTime(), medicalNum];

                                db.query(imageSql, imageParams, (err0, result0) => {
                                    console.log('result0', result0);
                                    if (err0) {
                                        throw err0;
                                        return;
                                    } else {
                                        // var sql = "INSERT INTO 'images' (medical_num) VALUES (?)";
                                        // db.query(sql, medicalNum, (err3, result3) => {
                                        //     if (err3) {
                                        //         throw err3;
                                        //         return;
                                        //     } else {
                                        //
                                        //     }
                                        // })

                                        var data = {
                                            url: imgPath + name,
                                            medicalNum: medicalNum,
                                            id: result0.insertId
                                        }
                                        callback1(null, data)
                                    }
                                })
                            }
                        })
                    })
                }, function (err, result) {
                    console.log('callback result', result);
                    res.send(result);
                })
            }
        })
    }
});

module.exports = router;